package com.bnyy.medicalHousekeeper.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.bnyy.gbp.customsView.ScaleImageView;
import com.bnyy.gbp.permission.PermissionHelper;
import com.bnyy.medicalHousekeeper.BuildConfig;
import com.bnyy.medicalHousekeeper.GlideHelper;
import com.bnyy.medicalHousekeeper.PopupWindowHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.bean.CheckUpdateInfo;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.HashSet;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AboutActivity extends BaseActivityImpl {
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tv_check_update)
    TextView tvCheckUpdate;
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;
    @BindView(R.id.iv_logo)
    ScaleImageView ivLogo;
    @BindView(R.id.tv_customer_service_phone)
    TextView tvCustomerServicePhone;


    @Override
    public int getLayoutId() {
        return R.layout.activity_about;
    }

    @Override
    public String getTitleStr() {
        return "  ";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tvVersion.setText("Version " + BuildConfig.VERSION_NAME + "." + BuildConfig.VERSION_CODE);
        if (!requestManager.isFormal()) {
            tvVersion.append("\n测试环境");
        }
        tvAgreement.setText(getString(R.string.app_name) + "软件许可及服务协议\n《隐私保护指引》");
        tvAgreement.setVisibility(View.GONE);

        GlideHelper.setRoundImage(mContext, R.mipmap.icon_logo_yygj, ivLogo);

        SpanUtils.with(tvCustomerServicePhone)
                .append("客服电话：")
                .append("020-31383938").setForegroundColor(Color.BLUE)
                .create();
        tvCustomerServicePhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionHelper.getInstance().requestPermission(new PermissionHelper.RequestPermission() {
                    @Override
                    public String[] permissions() {
                        return new String[]{Manifest.permission.CALL_PHONE};
                    }

                    @Override
                    public void granted(HashSet<String> granted) {
                        new XPopup.Builder(mContext).asBottomList("客服电话", new String[]{"020-31383938"},
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        Intent callIntent = new Intent(Intent.ACTION_CALL);
                                        Uri data = Uri.parse("tel:" + text);
                                        callIntent.setData(data);
                                        startActivity(callIntent);
                                    }
                                }).show();
                    }

                    @Override
                    public void denied(HashSet<String> denied) {

                    }
                });
//                PopupWindowHelper.getInstance(mContext).showCallPopupWindow("020-31383938");
            }
        });
    }

    @OnClick({R.id.tv_check_update, R.id.tv_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_check_update:
                checkUpdate();
                break;
            case R.id.tv_agreement:
                WebViewActivity.show(mContext, "https://www.bainianyang.com/html/h5/#/serve_agreement?id=1");
                break;
        }
    }

    private void checkUpdate() {
//        ProgressDialog progressDialog = ProgressDialog.show(mContext, "", "正在检测新版本");
        HashMap<String, Object> params = new HashMap<>();
        params.put("type", "android"); // 1 用户端 2 医护端 3 长护险管家 6 医养管家
        params.put("app_type", 6);
        params.put("app_version", BuildConfig.VERSION_NAME);
        requestManager.request(requestManager.mJavaRetrofitService.checkUpdate(RequestManager.getJsonRequestBody(params)),
                new BaseObserverImpl<CheckUpdateInfo>(mContext) {
                    @Override
                    public void onSuccess(CheckUpdateInfo checkUpdateInfo) {
                        super.onSuccess(checkUpdateInfo);
//                showDownloadDialog(checkUpdateInfo);
                        // force_upgrade_level 提示级别: 0不存在新版本；1存在新版本但不需要提示；2存在新版本提示用户升级；3存在新版本强制用户升级
                        switch (checkUpdateInfo.getForce_upgrade_level()) {
                            case 0:
                            case 1:
                                Toast.makeText(mContext, "已经是最新版本", Toast.LENGTH_SHORT).show();
                                break;
                            case 2:
                            case 3:
                                showDownloadDialog(checkUpdateInfo);
                                break;
                        }
                    }
                });
    }

    private void showDownloadDialog(CheckUpdateInfo checkUpdateInfo) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        View v = inflater.inflate(R.layout.dialog_update, null);
        AlertDialog alertDialog = builder.setCancelable(false)
                .setView(v)
                .create();
        TextView tvTitle = v.findViewById(R.id.tv_title);
        TextView tvUpdateContent = v.findViewById(R.id.tv_update_content);
        TextView tvCancel = v.findViewById(R.id.tv_cancel);
        tvTitle.append(checkUpdateInfo.getVersion());
        tvUpdateContent.setText(checkUpdateInfo.getDesc());

        if (checkUpdateInfo.getForce_upgrade_level() == 3) {
            tvCancel.setVisibility(View.GONE);
        } else {
            tvCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                }
            });
        }
        v.findViewById(R.id.tv_update).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
//                File target = new File(Environment.getExternalStorageDirectory(), "bnyy/apk/health_" + checkUpdateInfo.getVersion() + ".apk");
//                if (!target.getParentFile().exists()) {
//                    target.getParentFile().mkdirs();
//                }
                download(checkUpdateInfo.getDownload_url(), new File(getExternalCacheDir(), "health_" + checkUpdateInfo.getVersion() + ".apk").getAbsolutePath());
            }
        });

        alertDialog.show();
        v.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Window window = alertDialog.getWindow();
                window.setBackgroundDrawableResource(android.R.color.transparent);
                WindowManager.LayoutParams attributes = window.getAttributes();
                attributes.width = ScreenUtils.getScreenWidth() / 5 * 4;
                int height = ScreenUtils.getScreenHeight() / 5 * 4;

                if (v.getHeight() > height) {
                    attributes.height = height;
                }
                window.setAttributes(attributes);
                v.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
//        Window window = alertDialog.getWindow();
//        window.setBackgroundDrawableResource(android.R.color.transparent);
//        WindowManager.LayoutParams attributes = window.getAttributes();
//        int[] screenSize = ScreenUtils.getScreenSize(mContext);
//        attributes.width = screenSize[0] / 5 * 4;
//        attributes.height = screenSize[1] / 5 * 4;
//        window.setAttributes(attributes);
    }

    private void download(String url, String path) {
        requestManager.mRetrofitService.download(url).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                saveFile(response.body(), path);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.isShowing();
                }
                checkUpdate();
            }
        });
    }

    /**
     * 将文件写入本地
     *
     * @param responseBody 请求结果全体
     * @return 写入完成的文件
     */
    public void saveFile(ResponseBody responseBody, String path) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                InputStream is = null;
                byte[] buf = new byte[2048];
                int len;
                FileOutputStream fos = null;
                try {
                    is = responseBody.byteStream();
                    final long total = responseBody.contentLength();
                    long sum = 0;

                    Message message = handler.obtainMessage();
                    message.what = 0;
                    message.obj = (int) (total / 1000);
                    handler.sendMessage(message);

                    NumberFormat nf = NumberFormat.getPercentInstance();
                    //设置百分数精确度2即保留两位小数
                    nf.setMinimumFractionDigits(0);

                    File file = new File(path);
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        sum += len;
                        fos.write(buf, 0, len);

                        Message message1 = handler.obtainMessage();
                        message1.what = 1;
                        float progress = ((float) sum) / total;
                        message1.obj = (int) (sum / 1000);
                        handler.sendMessage(message1);
                    }
                    Message message2 = handler.obtainMessage();
                    message2.what = 2;
                    message2.obj = path;
                    handler.sendMessage(message2);
                    fos.flush();

                } catch (IOException e) {
                    Message message3 = handler.obtainMessage();
                    message3.what = 3;
                    handler.sendMessage(message3);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    ProgressDialog progressDialog;
    Handler handler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (progressDialog == null) {
                        progressDialog = new ProgressDialog(mContext);
                        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        progressDialog.setCancelable(false);
                        progressDialog.setTitle("正在下载");
                        progressDialog.setMax((Integer) msg.obj);
                        progressDialog.setIcon(R.mipmap.icon_logo);
                        progressDialog.show();
                    }
                    break;
                case 1:
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.setProgress((Integer) msg.obj);
                    }
                    break;
                case 2:
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    installApk((String) msg.obj);
                    break;
                case 3:
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    Toast.makeText(mContext, "安装包下载失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    public void installApk(String downloadApk) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(downloadApk);
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            uri = Uri.fromFile(file);
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        startActivity(intent);
    }
}
















































